<template>
  <div class="chat-container">
    <!-- 左侧联系人面板 -->
    <div class="contacts-panel">
      <div class="user-header">
        <div class="user-info">
          <el-avatar :size="40" :src="chatStore.currentUser?.avatar" />
          <div class="user-details">
            <div class="username">{{ chatStore.currentUser?.name }}</div>
            <div class="connection-status" :class="chatStore.connectionStatus">
              {{ connectionStatusDisplay }}
            </div>
          </div>
        </div>
        <div class="connection-controls">
          <el-button
              v-if="chatStore.connectionStatus !== 'connected'"
              type="primary"
              size="small"
              @click="connect"
          >
            连接
          </el-button>
          <el-button
              v-else
              type="danger"
              size="small"
              @click="disconnect"
          >
            断开
          </el-button>
        </div>
      </div>

      <el-tabs v-model="activeContactTab" stretch>
        <el-tab-pane label="私聊" name="private">
          <contact-list
              type="private"
              :contacts="chatStore.contacts.private"
              @select="setActiveSession('private', $event)"
          />
        </el-tab-pane>
        <el-tab-pane label="群组" name="groups">
          <contact-list
              type="group"
              :contacts="chatStore.contacts.groups"
              @select="setActiveSession('group', $event)"
          />
          <div class="group-controls">
            <el-button type="primary" size="small" @click="showCreateGroupDialog = true">
              创建群组
            </el-button>
            <el-button type="success" size="small" @click="showJoinGroupDialog = true">
              加入群组
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="系统" name="system">
          <contact-list
              type="system"
              :contacts="chatStore.contacts.system"
              @select="setActiveSession('global', null)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div v-if="chatStore.activeSession.id" class="chat-header">
        <el-avatar :size="40" :src="chatStore.activeSession.avatar" />
        <div class="session-info">
          <div class="session-name">{{ chatStore.activeSession.name }}</div>
<!--          <div class="session-status">-->
<!--            <span v-if="chatStore.activeSession.type === 'private'">-->
<!--              {{ getOnlineStatus(chatStore.activeSession.id) }}-->
<!--            </span>-->
<!--            <span v-else-if="chatStore.activeSession.type === 'group'">-->
<!--              {{ getGroupMemberCount(chatStore.activeSession.id) }} 成员-->
<!--            </span>-->
<!--          </div>-->
        </div>
      </div>

      <div class="message-container" ref="messageContainer">
        <template v-if="chatStore.activeSession.id">
          <message-list
              :messages="chatStore.currentMessages"
              :current-user-id="chatStore.currentUser?.id"
          />
        </template>

        <div v-else class="welcome-screen">
          <h3>欢迎使用聊天系统</h3>
          <p>选择一个联系人开始聊天</p>
          <el-button type="primary" @click="sendGlobalMessage('大家好！')">
            发送全局消息
          </el-button>
        </div>
      </div>

      <div v-if="chatStore.activeSession.id" class="message-input">
        <div class="input-tools">
          <el-tooltip content="发送图片">
            <el-button circle plain icon="Picture" />
          </el-tooltip>
          <el-tooltip content="发送文件">
            <el-button circle plain icon="Document" />
          </el-tooltip>
          <el-tooltip content="表情符号">
            <el-button circle plain icon="Smiley" />
          </el-tooltip>
        </div>
        <el-input
            v-model="messageInput"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keydown.enter.exact.prevent="sendMessage"
        />
        <div class="send-button">
          <el-button
              type="primary"
              :loading="sending"
              @click="sendMessage"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 创建群组对话框 -->
    <el-dialog v-model="showCreateGroupDialog" title="创建新群组">
      <el-form :model="newGroupForm" label-width="80px">
        <el-form-item label="群组名称">
          <el-input v-model="newGroupForm.name" placeholder="输入群组名称" />
        </el-form-item>
        <el-form-item label="选择成员">
          <el-select
              v-model="newGroupForm.members"
              multiple
              placeholder="选择成员"
          >
            <el-option
                v-for="contact in chatStore.contacts.private"
                :key="contact.id"
                :label="contact.name"
                :value="contact.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="createGroup">创建</el-button>
      </template>
    </el-dialog>

    <!-- 加入群组对话框 -->
    <el-dialog v-model="showJoinGroupDialog" title="加入群组">
      <el-form :model="joinGroupForm" label-width="80px">
        <el-form-item label="群组ID">
          <el-input v-model="joinGroupForm.groupId" placeholder="输入群组ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showJoinGroupDialog = false">取消</el-button>
        <el-button type="primary" @click="joinGroup">加入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/stores/chatStore.js'
import ContactList from './ContactList.vue'
import MessageList from './MessageList.vue'

// 使用 Pinia store
const chatStore = useChatStore()


// 从 store 中解构方法
const {
  connect,
  disconnect,
  setActiveSession,
  getOnlineStatus,
  getGroupMemberCount,
  sendGlobalMessage,
  sendPrivateMessage,
  sendGroupMessage,
  createGroup: storeCreateGroup,
  joinGroup: storeJoinGroup
} = chatStore

// 本地状态
const messageInput = ref('')
const sending = ref(false)
const messageContainer = ref(null)
const activeContactTab = ref('private')
const showCreateGroupDialog = ref(false)
const showJoinGroupDialog = ref(false)
const newGroupForm = ref({ name: '', members: [] })
const joinGroupForm = ref({ groupId: '' })

// 计算属性
const connectionStatusDisplay = computed(() => {
  const statusMap = {
    'disconnected': '未连接',
    'connecting': '连接中...',
    'connected': '在线',
    'error': '连接错误'
  }
  return statusMap[chatStore.connectionStatus] || '未知状态'
})

// 消息发送方法
const sendMessage = async () => {
  if (!messageInput.value.trim()) return

  const session = chatStore.activeSession
  const content = messageInput.value
  messageInput.value = ''
  sending.value = true

  try {
    if (session.type === 'private') {
      await sendPrivateMessage(session.id, content)
    } else if (session.type === 'group') {
      await sendGroupMessage(session.id, content)
    } else if (session.type === 'global') {
      await sendGlobalMessage(content)
    }
  } catch (error) {
    console.error('消息发送失败:', error)
  } finally {
    sending.value = false
  }
}

// 创建群组
const createGroup = async () => {
  if (!newGroupForm.value.name || newGroupForm.value.members.length === 0) return
  await storeCreateGroup(newGroupForm.value.name, newGroupForm.value.members)
  showCreateGroupDialog.value = false
  newGroupForm.value = { name: '', members: [] }
}

// 加入群组
const joinGroup = async () => {
  if (!joinGroupForm.value.groupId) return
  await storeJoinGroup(joinGroupForm.value.groupId)
  showJoinGroupDialog.value = false
  joinGroupForm.value.groupId = ''
}
</script>


<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background-color: #f5f7fa;
}

.contacts-panel {
  width: 300px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.user-header {
  padding: 15px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 12px;
}

.username {
  font-weight: 600;
  font-size: 16px;
}

.connection-status {
  font-size: 12px;
  color: #999;
}

.connection-status.connected {
  color: #67c23a;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  background-color: #fff;
}

.session-info {
  margin-left: 12px;
}

.session-name {
  font-weight: 600;
  font-size: 16px;
}

.session-status {
  font-size: 12px;
  color: #999;
}

.message-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.welcome-screen {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
}

.message-input {
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
}

.input-tools {
  display: flex;
  margin-bottom: 10px;
}

.send-button {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.group-controls {
  padding: 10px;
  display: flex;
  justify-content: space-around;
  border-top: 1px solid #f0f0f0;
}
</style>